﻿/* $RCSFile: HeaderMenu.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/UI/WebControls/HeaderMenu.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:30  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Globalization;

using AddonNice.Diagnostics;
using AddonNice.Settings;
using AddonNice.Core;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Helpers;
using AddonNice.Security;
using AddonNice.Configuration;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.UI.WebControls
{

    /// <summary>
    /// Provides a header menu to install in a page, most often in the design page with AddonNicePanes
    /// </summary>
    public class HeaderMenu : DataList
	{
		private object innerDataSource	= null;

		private bool _showLogon			= false;
		private bool _showSecureLogon	= false;   // no more used
		private bool _showHome			= true;
        private bool _showOrganization =   false;
		private bool _ShowPagesMan	    = true;
		
		private bool _showEditProfile	= true; 
		private bool _showWelcome		= true; 
		private bool _showLogOff		= true; 
		private bool _showSaveDesktop	= true; 
		private bool _dataBindOnInit	= true;

		private bool _showHelp			= false;	// link for show help window
		
		/// <summary>
		/// If true shows a link to a Help Window
		/// </summary>
		[Category("Data"),
		PersistenceMode(PersistenceMode.Attribute),
		DefaultValue(false)
		]
		public bool ShowHelp
		{
			get
			{
				return _showHelp;
			}
			set
			{
				_showHelp = value;
			}
		}

		/// <summary>
		/// If true shows a link to edit current page if in admin mode and user has edit rights
		/// </summary>
		[Category("Data"),
		PersistenceMode(PersistenceMode.Attribute),
		DefaultValue(true)
		]
		public bool ShowPagesMan
		{
			get
			{
				return _ShowPagesMan;
			}
			set
			{
				_ShowPagesMan = value;
			}
		}

		/// <summary>
		/// If true and user is not authenticated shows 
		/// a logon link in place of logoff
		/// </summary>
		[Category("Data"),
		PersistenceMode(PersistenceMode.Attribute),
		DefaultValue(false)
		]
		public bool ShowLogon
		{
			get
			{
				return _showLogon;
			}
			set
			{
				_showLogon = value;
			}
		}
 
		/// <summary>
		/// No more used: ShowLogon automatically switch according PortalIsSecured setting in UrlBuilder
		/// </summary>
		[Category("Data"),
		PersistenceMode(PersistenceMode.Attribute),
		DefaultValue(false)
		]
		public bool ShowSecureLogon
		{
			get
			{
				return _showSecureLogon;
			}
			set
			{
				_showSecureLogon = value;
			}
		}

		/// <summary>
		/// Weither show home link
		/// </summary>
		[DefaultValue(true)]
		public bool ShowHome
		{
			get
			{
				return _showHome;
			}
			set
			{
				_showHome = value;
			}
		}
		
		/// <summary>
		/// Weither show home link
		/// </summary>
		[DefaultValue(true)]
		public bool ShowOrganization
		{
			get
			{
				return _showOrganization;
			}
			set
			{
				_showOrganization = value;
			}
		}
		
		
		/// <summary>
		/// Wether Edit Profile link
		/// </summary>
		[DefaultValue(true)]
		public bool ShowEditProfile
		{
			get
			{
				return _showEditProfile;
			}
			set
			{
				_showEditProfile = value;
			}
		}

		/// <summary>
		/// Weither Welcome Shows
		/// </summary>
		[DefaultValue(true)]
		public bool ShowWelcome
		{
			get
			{
				return _showWelcome;
			}
			set
			{
				_showWelcome = value;
			}
		}

		/// <summary>
		/// Weither Logoff Link Shows
		/// </summary>
		[DefaultValue(true)]
		public bool ShowLogOff
		{
			get
			{
				return _showLogOff;
			}
			set
			{
				_showLogOff = value;
			}
		}

		/// <summary>
		/// Weither Logoff ShowSaveDesktop Shows
		/// </summary>
		[DefaultValue(true)]
		public bool ShowSaveDesktop
		{
			get
			{
				return _showSaveDesktop;
			}
			set
			{
				_showSaveDesktop = value;
			}
		}

		/// <summary>
		/// Should bind in OnInit
		/// </summary>
		[DefaultValue(true)]
		public bool DataBindOnInit
		{
			get
			{
				return _dataBindOnInit;
			}
			set
			{
				_dataBindOnInit = value;
			}
		}
		
		/// <summary>
        /// HeaderMenu
        /// </summary>
		public HeaderMenu()
		{
			EnableViewState = false;
			RepeatDirection = RepeatDirection.Horizontal;
		}

		protected override void OnInit(EventArgs e)
		{
            if (WebControlsTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenu OnInit BEG DataBindOnInit: {0}",DataBindOnInit),WebControlsTraceSwitch.Sw.Info);
            if ( PortalSettings.IsUnderCRM )
                Visible =   false;
 			if( DataBindOnInit )
			{
				DataBind();
			}
            //base.OnInit(e);
            if (WebControlsTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]HeaderMenu OnInit END.",WebControlsTraceSwitch.Sw.Info);
        }

		/// <summary>
		/// Builds a help link for the header menu and registers it with the page
		/// </summary>
		private string GetHelpLink()
		{
			string helpTarget       =   "AddonNiceHelp";
			string popupOptions     =   "toolbar=1,location=0,directories=0,status=0,menubar=1,scrollbars=1,resizable=1";
			string helpText         =   LocalizeHelper.NoBreakLocalize("HEADER_HELP", "Help");

			StringBuilder sb        =   new StringBuilder();
            string strHelpPath      =   Config.HelpPath.TrimStart(new char[]{'~','/'}); // remove '~/'
			sb.AppendFormat("<a href=\"{0}/{1}/HelpViewer.aspx\" target=\"{2}\"",
                            new object[]{Settings.Path.ApplicationRoot,strHelpPath,helpTarget}); 
            bool isADNPg               =   false;
			if ( Page is ADNPage )
			{
                isADNPg                =   true;
				sb.AppendFormat("onclick=\"help_popup(this,'{0}');return false;\"",popupOptions);
			}
			sb.Append(" class=\"link-is-popup");
			if ( CssClass != string.Empty )
			{
				sb.AppendFormat(" {0}",CssClass);
			}
			sb.AppendFormat("\">{0}</a>",helpText);

			if ( isADNPg )
			{
                string gPath    =   Path.ToAbsolute(Config.PortalScriptsPath+"/popup.js");
				((ADNPage)Page).RegisterADNClientScriptInclude("adn_popup",gPath);
			}
            string helpstr          =   sb.ToString();
            if (WebControlsTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenu DataBind helpLink: {0}",helpstr),WebControlsTraceSwitch.Sw.Info);
			return helpstr;
		}

		public override void DataBind()
		{
            if (WebControlsTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenu DataBind BEG ShowEditProfile: {0}, ShowHelp: {1}, ShowHome: {2}, ShowLogon: {3}, ShowLogOff: {4}, ShowPagesMan: {5}, ShowSaveDesktop: {6}, ShowWelcome: {7}, ShowOrganization: {8}", 
                    new object[]{ ShowEditProfile,ShowHelp,ShowHome,ShowLogon,ShowLogOff,ShowPagesMan,ShowSaveDesktop,ShowWelcome,ShowOrganization}),WebControlsTraceSwitch.Sw.Info);
            if (HttpContext.Current == null)
            {
			    base.DataBind ();
                return;
            }
			//Init data
			ArrayList list                  =   new ArrayList();

			// Obtain PortalSettings from Current Context
			PortalSettings portalSettings   =   (PortalSettings) HttpContext.Current.Items[StStr.strPortalSettings];
            StringBuilder sb                =   new StringBuilder();
			sb.Append("<a");
			if ( CssClass != string.Empty )
				sb.AppendFormat(" class=\"{0}\"",CssClass);

			string homeLink                 =   sb.AppendFormat(" href='{0}'>{1}</a>",
                HttpUrlBuilder.BuildUrl(),LocalizeHelper.NoBreakLocalize("HEADER_HOME", "Home")).ToString();
            if (WebControlsTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenu DataBind homeLink: {0}",homeLink),WebControlsTraceSwitch.Sw.Info);

            if (WebControlsTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenu DataBind Request.IsAuthenticated: {0}",HttpContext.Current.Request.IsAuthenticated),WebControlsTraceSwitch.Sw.Info);

            // If user logged in, customize welcome message
			if ( HttpContext.Current.Request.IsAuthenticated ) 
			{
                AuthenticationMode aMode    =   Config.AuthenticationMode;
				if ( ShowWelcome )
				{
                    string nm               =   string.Empty;
                    if ( aMode == AuthenticationMode.Forms)
                    {
                        AddonNiceIdentity usr   =   PortalSettings.GetCurrentPrincipal(false).AddonNiceIdentity;
                        nm                  =   usr.Name;
                    }
                    else if ( aMode == AuthenticationMode.Windows)
                    {
                        // 08/09 Pb with IIS7 we get NETWORK_SERVICES nm                  =   HttpContext.Current.Request.LogonUserIdentity.Name;
                        if ( ( HttpContext.Current.User != null ) && (HttpContext.Current.User.Identity != null ) )
                                nm          =   HttpContext.Current.User.Identity.Name;
                        else    nm          =   HttpContext.Current.Request.LogonUserIdentity.Name;

                    }
                    if (WebControlsTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenu DataBind IsAuthenticated user name: {0}",nm),WebControlsTraceSwitch.Sw.Info);
                    if ( nm != string.Empty )
                    {
                        string msg          =   LocalizeHelper.NoBreakLocalize("HEADER_WELCOME", "Welcome").Replace(" ",StStr.HTML_SPACE);
                        string str          =   string.Format("{0}&#160;{1}!", msg, nm);
                        if (WebControlsTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenu DataBind IsAuthenticated welcome: [{0}]",str),WebControlsTraceSwitch.Sw.Info);
                        list.Add(str);
                    }
				}
                if ( ShowOrganization && ( aMode == AuthenticationMode.Windows ) )
                {
                        string str          =   PortalSecurity.Wrapper.OrganizationFriendlyName;
                        if (WebControlsTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenu DataBind Organization: [{0}]",str),WebControlsTraceSwitch.Sw.Info);
                        list.Add(str);
                }

				if (ShowHome)
				{
					list.Add(homeLink);
				}
				if (ShowHelp)
				{
					list.Add(GetHelpLink());
				}
				
				// Find Page Manager module to see if the user has add/edit rights
				ModulesDB modules               =   new ModulesDB();
				Guid PageManGuid                =   new Guid(StStr.PortalPagesManagerGuid);
				// Modification to support Multi or zero Page Modules in a single portal.
				bool HasEditPermissionsOnPages  =   false;
				int PageManModuleID             =   0;
                int ModID                       =   -1;
                try
                {
                    PageManModuleID             =   modules.GetModuleDefinitionByGuid(StStr.CommonPortalID, PageManGuid);
                    if (WebControlsTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenu DataBind PageManModuleID: {0}",PageManModuleID),WebControlsTraceSwitch.Sw.Info);

                    SqlDataReader dr            =   null;
                    try
                    {
                        dr                      =   modules.GetModulesByDefId(PageManModuleID);
                        if ( !dr.HasRows )
                        {
                            if (WebControlsTraceSwitch.Sw.TraceError)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenu DataBind ModID not found PageManModuleID: {0}",PageManModuleID),WebControlsTraceSwitch.Sw.Info);
                        }
                        else
                        {
                            dr.Read();
                            ModID               =   (int)dr[StStr.DBModuleID];
                            if (WebControlsTraceSwitch.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenu DataBind ModID: {0}",ModID),WebControlsTraceSwitch.Sw.Info);
                        }
                    }
                    catch(Exception ex)
                    {
                        if (WebControlsTraceSwitch.Sw.TraceError)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]HeaderMenu GetModulesByDefId ex:{0}", ex),WebControlsTraceSwitch.Sw.Info);
                        throw;
                    }
                    finally
                    {
                        if ( dr != null )
                            dr.Close();
                    }
                    if (ModID != -1)
                    {
                        ModuleConfiguration ms           =   new ModuleConfiguration(ModID);
                        if (WebControlsTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenu DataBind ms.AuthorizedEditRoles: {0}", ms.AuthorizedEditRoles), WebControlsTraceSwitch.Sw.Info);
                        HasEditPermissionsOnPages   =   PortalSecurity.IsUserInRoles(ms.AuthorizedEditRoles);
                        if (WebControlsTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenu DataBind HasEditPermissionsOnPages: {0}", HasEditPermissionsOnPages), WebControlsTraceSwitch.Sw.Info);
                    }
                }
                catch(Exception ex)
                {
                    if (WebControlsTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]HeaderMenu DataBind ex:{0}", ex),WebControlsTraceSwitch.Sw.Info);
                    throw;
                }
                sb                              =   new StringBuilder();
                if (WebControlsTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenu DataBind IsAdminPortal: {0}",Config.IsAdminPortal),WebControlsTraceSwitch.Sw.Info);
                // If admin portal and user logged in and has Edit permission in the PageManager module, reach tab management just one click
				if ( Config.IsAdminPortal && 
                    ShowPagesMan && HasEditPermissionsOnPages )
				{
					sb.Append("<a");
					if ( CssClass != string.Empty)
						sb.AppendFormat(" class=\"{0}\"", CssClass);

					sb.AppendFormat(" href='{0}'>{1}</a>", 
                        new object[]{
                                HttpUrlBuilder.BuildUrl(Config.ModulesPath+"/"+Config.PageLayoutPage,portalSettings.ActivePageSettings.PageID,ModID,
                                    string.Format("{0}={1}",StStr.returnPageID,portalSettings.ActivePageSettings.PageID),portalSettings.BaseAlias), 
						        LocalizeHelper.NoBreakLocalize("HEADER_MANAGE_PAGE", "Edit This Page")
                                });
                    string showPageManLnk   =   sb.ToString();
                    if (WebControlsTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenu DataBind showPageManLnk: {0}",showPageManLnk),WebControlsTraceSwitch.Sw.Info);
					list.Add(showPageManLnk); 
				}
				// user is authenticated -> add edit user profile link
                if (WebControlsTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenu DataBind ShowEditProfile: {0}",ShowEditProfile),WebControlsTraceSwitch.Sw.Info);
                if ( ShowEditProfile )
                {
					sb                      =   new StringBuilder();
					sb.Append("<a");
					if (CssClass != string.Empty)
						sb.AppendFormat(" class=\"{0}\"",CssClass);
                    string editurl          =   portalSettings.DefaultEditProfilePageUrl;
					sb.AppendFormat(" href='{0}' >{1}</a>",editurl,LocalizeHelper.NoBreakLocalize("HEADER_EDIT_PROFILE", "Edit profile"));
                    string editProfileLnk   =   sb.ToString();
                    if (WebControlsTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenu DataBind editProfileLnk: {0}",editProfileLnk),WebControlsTraceSwitch.Sw.Info);
					list.Add(editProfileLnk); 
				}
                 
				// if authentication mode is Form, provide a logoff link
				if ( Config.AuthenticationMode == AuthenticationMode.Forms ) 
				{
					if (ShowLogOff)
					{
                        string href         =   HttpUrlBuilder.BuildUrl("~/Logoff.aspx",true,DynPageLoc.Login,StStr.PageLogoffID);

						sb                  =   new StringBuilder();
                        sb.Append("<a");
						if ( CssClass != string.Empty)
							sb.AppendFormat(" class=\"{0}\"",CssClass);

						sb.AppendFormat(" href='{0}'>{1}</a>",href,LocalizeHelper.NoBreakLocalize("HEADER_LOGOFF", "Logoff"));
                        string  logoffLnk   =   sb.ToString();
                        if (WebControlsTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenu DataBind logoffLnk: {0}",logoffLnk),WebControlsTraceSwitch.Sw.Info);
						list.Add(logoffLnk); 
					}
				}
				//-------------------------------------------------
				// This may be a little strange but the menu header
				// does not accept buttons (link/push/image/...) but
				// references (strings). So in order for me to get a
				// callback, not calling a .aspx page, I simply get 
				// a link button that is in the skin and insert a
				// callback (provided by .net) w/ the proper name
				// in the reference as done above. This way I get
				// the same affect but w/ a callback event
				//-------------------------------------------------
				// get the link button -- only need the link button even though
				// it is not visible. It's needed to provide a callback from
				// for this reference. So it is not in this datalist but just outside of it
				LinkButton lb   = Parent.FindControl("saveConfig") as LinkButton;
				// if there a button in the layouts
				if ( lb != null && 
					Config.SupportWindowMgmt ) 
				{

					// If Statement and public/private property added by John Mandia 26th October
					if( ShowSaveDesktop )
					{
						// set the callback to handle the save
						lb.Click += new EventHandler(this.HandleSave);
						// convert the name for the postback to understand -- the
						// control it will be calling
						string lb_id = lb.UniqueID.Replace(":","$");
						// insert the  callback/postback
						// added Class support by Mario Endara <mario@softworks.com.uy> 2004/10/04
						sb  =   new StringBuilder();
                        sb.Append("<a");
						if ( CssClass != string.Empty)
							sb.AppendFormat(" class=\"{0}\"",CssClass);

						sb.AppendFormat(" href=\"javascript:__doPostBack('{0}','')\">{1}</a>",
                            lb_id,LocalizeHelper.NoBreakLocalize("HEADER_SAVE_DESKTOP", "Save Desktop"));
						list.Add(sb.ToString()); 
					}
				}
			}
			else  // user not logged in-> shoud be in formAuthentication
			{
				if (ShowHome)
				{
					list.Add(homeLink); 
				}

				if (ShowHelp)
				{
					list.Add(GetHelpLink());
				}
				
				// if not authenticated and ShowLogon is true, provide a logon link 
				if (ShowLogon )
                {
					sb                  =   new StringBuilder();
                    sb.Append("<a");
					if ( CssClass != string.Empty)
						sb.AppendFormat(" class=\"{0}\"",CssClass);
                    
                    //string returl       =   string.Format("ReturnUrl={0}",Page.Server.UrlEncode(Page.Request.Url.GetLeftPart(UriPartial.Path)));
                    int loginPdId       =   portalSettings.CustomSettings[StStr.SiteDefaultLoginPage].ToInt();
                    string href         =   HttpUrlBuilder.BuildUrl("~/Login.aspx",true,DynPageLoc.Login,loginPdId);

					sb.AppendFormat(" href='{0}'>{1}</a>",href,LocalizeHelper.NoBreakLocalize("HEADER_LOGON", "Logon"));
                    string logonLnk     =   sb.ToString();
                    if (WebControlsTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenu DataBind logonLnk: {0}",logonLnk),WebControlsTraceSwitch.Sw.Info);
					list.Add(logonLnk); 
				}
			}
			innerDataSource             =   list;
			base.DataBind ();
            if (WebControlsTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]HeaderMenu DataBind END.",WebControlsTraceSwitch.Sw.Info);
		}


        public override object DataSource
        {
            get
            {
                if (WebControlsTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenu DataSource GET innerDataSource: {0}",innerDataSource.ToString()),WebControlsTraceSwitch.Sw.Info);
                return innerDataSource;
            }
            set
            {
                if (WebControlsTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HeaderMenu DataSource SET innerDataSource: {0}",value.ToString()),WebControlsTraceSwitch.Sw.Info);
                innerDataSource = value;                
            }
        }

		/// <summary>
		/// Handles the button event to save desktop
		/// </summary>
		private void HandleSave(object sender, EventArgs evt)
		{
			// go save user desktop
			BLL.UserConfig.UserDesktop.SaveUserDesktop();
		} // end of HandleSave
    }
}